package com.zmn.oms.third.youshu.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zmn.oms.common.utils.HttpUtil;
import com.zmn.oms.third.youshu.YouShuConsts;
import com.zmn.oms.third.youshu.dto.YouShuRequest;
import com.zmn.oms.third.youshu.dto.YouShuResponse;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * 类描述：腾讯有数工具类
 *
 * @author ligang
 * @since 2022/3/22 12:41
 */
@Slf4j
public class YouShuUtils {

    /**
     * 请求数据进行sha256签名
     *
     * @param request
     */
    private static String makeSign(YouShuRequest request) {
        Random random = new Random(System.currentTimeMillis());
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String nonce = String.valueOf(Math.abs(random.nextLong()));

        String str = String.format("app_id=%s&nonce=%s&sign=%s&timestamp=%s", YouShuConsts.APP_ID, nonce, YouShuConsts.SIGN, timestamp);
        Mac mac;
        StringBuilder hexStringBuilder = new StringBuilder();
        try {
            mac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKey = new SecretKeySpec(YouShuConsts.APP_SECRET.getBytes(StandardCharsets.UTF_8), mac.getAlgorithm());
            mac.init(secretKey);
            byte[] bytes = mac.doFinal(str.getBytes(StandardCharsets.UTF_8));
            hexStringBuilder.setLength(0);
            for (byte aByte : bytes) {
                String hex = Integer.toHexString(0xff & aByte);
                if (hex.length() == 1) {
                    hexStringBuilder.append('0');
                }
                hexStringBuilder.append(hex);
            }
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
        }
        String signature = hexStringBuilder.toString();
        log.info("【{}】生成签名【{}】", YouShuConsts.CHANNEL_NAME, signature);

        // 设置请求参数
        request.setAppId(YouShuConsts.APP_ID);
        request.setTimestamp(timestamp);
        request.setSign(YouShuConsts.SIGN);
        request.setTimestamp(timestamp);
        request.setSignature(signature);
        return str + "&signature=" + signature;
    }

    /**
     * 发送数据上报请求
     */
    public static YouShuResponse sendGetRequest(String url, YouShuRequest request) {
        String params = makeSign(request);
        String pathRequest = YouShuConsts.HOST + url + "?" + params;
        try {
            log.info("【{}-API】<API请求> Url:[{}] RequestBody:[{}]", YouShuConsts.CHANNEL_NAME, pathRequest, JSON.toJSON(request));
            String res = HttpUtil.httpsGet(pathRequest);
            log.info("【{}-API】<API响应> ResponseBody:[{}]", YouShuConsts.CHANNEL_NAME, res);
            return JSONObject.parseObject(res, YouShuResponse.class);
        } catch (Exception e) {
            log.info("【{}-API】 请求失败:[{}]", YouShuConsts.CHANNEL_NAME, e.getMessage());
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 发送数据上报请求
     */
    public static YouShuResponse sendRequest(String url, YouShuRequest request) {
        String params = makeSign(request);
        String pathRequest = YouShuConsts.HOST + url + "?" + params;
        try {
            log.info("【{}-API】<API请求> Url:[{}] RequestBody:[{}]", YouShuConsts.CHANNEL_NAME, pathRequest, JSON.toJSON(request));
            String res = HttpUtil.httpsPost(pathRequest, JSON.toJSONString(request));
            log.info("【{}-API】<API响应> ResponseBody:[{}]", YouShuConsts.CHANNEL_NAME, res);
            return JSONObject.parseObject(res, YouShuResponse.class);
        } catch (Exception e) {
            log.info("【{}-API】 请求失败:[{}]", YouShuConsts.CHANNEL_NAME, e.getMessage());
            log.error(e.getMessage(), e);
            return null;
        }
    }
}
